/**
 * Created by zhangsong on 2019-05-08.
 */

import React, { Component } from 'react';
import { Button, Form, Input, Radio, Select, Tooltip, Icon, Spin, DatePicker } from 'antd';
import { connect } from 'dva';
import { formatMessage, FormattedMessage, getLocale } from '@/utils/i18n';
import AlarmReducer from '@/dva/application/alarmemail';
import UserReducer from '@/dva/user';
import moment from 'moment';
import Style from './search.module.scss';

const { Namespace, Effects } = AlarmReducer;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

@connect(
  state => ({
    contractorStore: state[Namespace],
    userStore: state[UserReducer.Namespace],
  }),
  dispatch => ({
    getAlarmemailList: data =>
      dispatch({
        type: `${Namespace}/${Effects.getAlarmemailList}`,
        data,
      }),
    downLoadXlsx: data =>
      dispatch({
        type: `${Namespace}/${Effects.downLoadXlsx}`,
        data,
      }),
  }),
)
@Form.create()
class SearchApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dates: [],
      mindate: '',
    };
  }

  componentDidMount() {
    const { getAlarmemailList, form } = this.props;
    getAlarmemailList({
      page: 1,
      pageSize: 10,
      startTime: `${moment(form.getFieldValue('time')[0]).format(dateFormat)} 00:00:00`,
      endTime: `${moment(form.getFieldValue('time')[1]).format(dateFormat)} 23:59:59`,
      passNumber: '',
    });
    this.timer = setInterval(
      () => {
        getAlarmemailList({
          page: 1,
          pageSize: 10,
          startTime: form.getFieldValue('time') ? `${moment(form.getFieldValue('time')[0]).format(dateFormat)} 00:00:00` : null,
          endTime: form.getFieldValue('time') ? `${moment(form.getFieldValue('time')[1]).format(dateFormat)} 23:59:59` : null,
          passNumber: form.getFieldValue('passNumber'),
        });
      },
      600000,
    );
  }

  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
  }

  handleClear = () => {
    const { form } = this.props;
    form.setFieldsValue({
      passNumber: undefined,
      time: undefined,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, getAlarmemailList } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        console.log('看看安娜', values)
        getAlarmemailList(
          {
            page: 1,
            pageSize: 10,
            startTime: values.time ? `${moment(values.time[0]).format(dateFormat)} 00:00:00` : null,
            endTime: values.time ? `${moment(values.time[1]).format(dateFormat)} 23:59:59` : null,
            passNumber: values.passNumber,
          },
        )
      }
    });
  };

  onDownload = () => {
    // this.props.onDownload();
    const { downLoadXlsx, form } = this.props;
    downLoadXlsx({
      startTime: form.getFieldValue('time') ? `${moment(form.getFieldValue('time')[0]).format(dateFormat)} 00:00:00` : null,
      endTime: form.getFieldValue('time') ? `${moment(form.getFieldValue('time')[1]).format(dateFormat)} 23:59:59` : null,
    })
  };

  disabledDate = time => {
    const { dates, mindate } = this.state;
    if (!time) {
      return false
    }
    const res = 7 * 24 * 3600 * 1000; // 这里如果乘以15相当于限制16天以内的  所以乘以14
    // 当前日期 - res = 15天之前
    const minTime = new Date(mindate).getTime() - res;
    // 当前日期 + res = 15天之后
    const maxTime = new Date(mindate).getTime() + res;
    return new Date(time).getTime() < minTime || new Date(time).getTime() > maxTime;
    // // 限制三个月内
    // const timeRange = time < moment().subtract(3, 'month') || time > moment().add(3, 'm');
    // // 只能选择七天
    // const tooLate = dates[0] && time.diff(dates[0], 'days') > 7;
    // const tooEarly = dates[1] && (dates[1]).diff(time, 'days') > 7;
    // console.log('看看是否隐藏数据', dates, time.diff(dates[0], 'days'))
    // return timeRange || tooEarly || tooLate;
  };

  render() {
    const { form, userStore = {}, exloading } = this.props;
    const { getFieldDecorator } = form;
    // const { recordDate } = this.state;
    const { area } = userStore;
    const zoneTips = Array.isArray(area) ? (
      <div className={Style.zoneTipsWrapper}>
        {area.map(item => (
          <div
            key={item.id + (getLocale() === 'en-US' ? item.areaDescEn : item.areaDescZh)}
            className={Style.zoneTipsRow}
          >
            <div className={Style.zoneTipsLabel}>{item.areaCode}</div>
            <div>=</div>
            <div>{getLocale() === 'en-US' ? item.areaDescEn : item.areaDescZh}</div>
          </div>
        ))}
      </div>
    ) : null;
    return (
      <div className={Style.searchFormWrapper}>
        <div style={{ display: 'flex', justifyContent: 'end', padding: '0 0 10px' }}>
          <Button loading={exloading} htmlType="button" icon="download" onClick={() => this.onDownload()}>
            {formatMessage('button.newdownload')}
          </Button>
        </div>
        {/* <></> */}
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <div className="item-wrapper">
            <Form.Item label={formatMessage({
              id: 'user-login.date.label',
            })}>
              {getFieldDecorator('time', {
                initialValue: [moment(moment(new Date().getTime() - 3600 * 1000 * 24 * 2).format(dateFormat), dateFormat),
                moment(new Date(), dateFormat)],
              })(
                <RangePicker
                  onCalendarChange={val => {
                    if (val[0]) {
                      this.setState({
                        dates: val,
                        mindate: val[0],
                      })
                    }
                    if (val[1]) {
                      this.setState({
                        dates: val,
                        mindate: '',
                      })
                    }
                  }}
                  disabledDate={this.disabledDate}
                  format={dateFormat}
                  allowClear={false}
                />,
              )}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item
              label={formatMessage('applicationCommon.readerCard.passno')}
            >
              {getFieldDecorator('passNumber', {})(<Input />)}
            </Form.Item>
          </div>
          <div className="item-wrapper"></div>
          <div className="item-wrapper search-button">
            <Button htmlType="button" onClick={this.handleClear}>
              {formatMessage('button.clear')}
            </Button>
            <Button type="primary" htmlType="submit">
              {formatMessage('button.search')}
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}

export default SearchApp;
